﻿using Extention.ENode.Cache;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Extention.ENode.Rpc.Runtime.Server.Impl
{
    public class DefaultServiceHostBalance : IServiceHostBalance
    {

        private readonly string HostBalanceKEY = "PLA:HOSTBALANCEKEY";
        private int Db = 11;
        private readonly ILogger<DefaultServiceHostBalance> _logger;

        private readonly ICacheProvider _cacheProvider;
        public DefaultServiceHostBalance(ILogger<DefaultServiceHostBalance> logger, ICacheProvider cacheProvider)
        {
            _cacheProvider = cacheProvider;
            _logger = logger;
        }

        public Task ClearAsync()
        {
            throw new NotImplementedException();
        }

        public async Task<IEnumerable<RouteBalanceModel>> GetHostBalance()
        {
            var isHave = _cacheProvider.KeyExists(HostBalanceKEY, Db);
            if (isHave)
            {
                try
                {
                    var content = await _cacheProvider.StringGetAsync<List<RouteBalanceModel>>(HostBalanceKEY, Db);

                    return content;
                }
                catch (Exception exception)
                {
                    if (_logger.IsEnabled(LogLevel.Error))
                        _logger.LogError("获取HOST失败！", exception);

                    return new List<RouteBalanceModel>();
                }
            }
            else
            {
                return new List<RouteBalanceModel>();
            }
        }

        public async Task<RouteBalanceModel> GetOneHost()
        {
            var isHave = _cacheProvider.KeyExists(HostBalanceKEY, Db);
            if (isHave)
            {
                try
                {
                    var content = await _cacheProvider.StringGetAsync<List<RouteBalanceModel>>(HostBalanceKEY, Db);

                    if (content.Count > 0)
                    {
                        var LevelSum = content.Sum(n => n.Level);
                        var LevelPoint = content.Select(n => new
                        {
                            n.Level,
                            n.BalanceKey,
                            //  LevelPo  n.Level/ LevelSum
                        }).ToList();


                    }

                    return null;
                }
                catch (Exception exception)
                {
                    if (_logger.IsEnabled(LogLevel.Error))
                        _logger.LogError("获取HOST失败！", exception);

                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        public Task Remove(RouteBalanceModel route)
        {
            throw new NotImplementedException();
        }

        public async Task SetHostsBalance(RouteBalanceModel route)
        {

            var isHave = _cacheProvider.KeyExists(HostBalanceKEY, Db);
            if (isHave)
            {
                try
                {
                    var content = _cacheProvider.StringGet<List<RouteBalanceModel>>(HostBalanceKEY, Db);
                    content.Add(route);
                    await _cacheProvider.StringSetAsync(HostBalanceKEY, JsonConvert.SerializeObject(content), null, Db);
                    if (_logger.IsEnabled(LogLevel.Information))
                        _logger.LogInformation(
                            $"设置HOST服务成功！BalanceKEY：" + route.BalanceKey);
                }
                catch (Exception exception)
                {
                    if (_logger.IsEnabled(LogLevel.Error))
                        _logger.LogError("设置HOST失败！", exception);
                }

            }
            else
            {
                try
                {
                    List<RouteBalanceModel> routes = new List<RouteBalanceModel>() { route };
                    await _cacheProvider.StringSetAsync(HostBalanceKEY, JsonConvert.SerializeObject(routes), null, Db);
                    if (_logger.IsEnabled(LogLevel.Information))
                        _logger.LogInformation(
                            $"设置HOST服务成功！BalanceKEY：" + route.BalanceKey);
                }
                catch (Exception exception)
                {
                    if (_logger.IsEnabled(LogLevel.Error))
                        _logger.LogError("设置HOST失败！", exception);
                }

            }
        }
    }
}
